<template>
  <div class="article-content">
    <!-- 导航 -->
      <van-nav-bar
        title="文章详情"
        left-text="返回"
        left-arrow
        @click-left="$router.back()"
        class="nav-bar"
      />
      <!-- 文章正文 -->
      <div class="article-wrap">
          <h1 class="title">{{article.title}}</h1>
          <van-cell
          center
          class="cell-desc"
          >
            <van-image
                    class="avatar"
                    slot="icon"
                    round
                  fit="cover"
                    :src="article.aut_photo"
            />
              <div class="user-name" slot="title">{{article.aut_name}}</div>
              <p slot="label" class="pubdata">{{article.pubdate | relativeTime}}</p>
              <van-button
                :type="article.is_followed ? 'default ' : 'info'"
                round size="small"
                class="follow-btn"
                :icon="article.is_followed ? '':'plus'"
                :loading="isFollowLoading"
                @click="onFollow"
                >
                {{article.is_followed ? '已关注':'关注'}}

              </van-button>
          </van-cell>
          <!-- 内容 -->
          <div ref="article-content" class="content markdown-body" v-html="article.content"></div>
           <!-- 文章评论列表 -->
           <comment-list :source="articleId" :list='commtentList' @update-total-count='totalCommentCount=$event' @reply-click="onReply"/>
      </div>
      <!-- 底部区域 -->
      <div class="article-bottom">
          <van-button class="comment-btn" type="default" @click="popShow" round size="small">写评论</van-button>
           <van-icon name="comment-o" :info="totalCommentCount" color="#777"/>
           <van-icon
           :name="article.is_collected ? 'star':'star-o' "
           :color="article.is_collected ? 'orange':'#777'"
           @click="onCollected"
           />
           <van-icon
           :name="article.attitude===1 ? 'good-job':'good-job-o'"
           :color="article.attitude===1 ?  'orange':'#777'"
           @click="onLike"
           />
           <van-icon name="share" color="#777"/>
      </div>
      <!-- 发布评论 -->
      <van-popup v-model="isShow" position="bottom" >
          <post-comment :commentId='articleId' @post-success="onPostSuccess"/>
      </van-popup>
      <!-- 评论回复 -->
      <van-popup
       v-model="isReplyShow"
       position="bottom"
      >
         <!--
             这里使用v-if的目的是让组件随着弹出层的显示进行渲染和销毁，防止加载过的组件不重新渲染导致数据不更新

          -->
        <comment-reply :comment="replyComment" @colse="isReplyShow=false" v-if="isReplyShow" :art-id="articleId"></comment-reply>
      </van-popup>
  </div>
</template>
<script>
import {
  getArticleById,
  addCollected,
  delCollected,
  addLike,
  delLike } from '@/api/article.js'
import {addFollow,delFollow} from '@/api/user.js'
import '@/styles/github-markdown.css';
import { ImagePreview } from 'vant'; //必须单独加载
import commentList from './components/comment-list.vue'
import postComment from './components/post-comment.vue'
import commentReply from './components/comment-reply.vue'
//在组件中获取动态路由参数：
// 方式一 this.$route.params.xxx
//方式二  props传参（推荐）
export default {
  name: 'TlineNews',
  components: {
    commentList,
    postComment,
    commentReply
   },
  props:{
    articleId:{
      type:[String,Number,Object],
      required:true
    }
  },
  directives: { },

  data() {
    return {
        article:{}, //文章数据对象
        isFollowLoading:false, //关注用户的loading状态
        isShow:false,//控制弹出层
        commtentList:[],//文章评论列表
        totalCommentCount:0,//评论总数量
        isReplyShow:false, //控制回复的显示状态
        replyComment:{} //当前回复评论的数据
    };
  },

  mounted() {

  },
 created(){
   this.loadArticle()
 },
  methods: {
    async loadArticle(){
       const  { data } = await getArticleById(this.articleId)
       console.log(data)
       this.article=data.data
       //获取文章内容DOM容器
       //数据改变影响视图更新(DOM数据) 不是立即的
       //所以如果需要修改数据之后马上操作被该数据影响的视图DOM，需要把这个代码放到$nextTick中
       //得到所有的img标签
       //this.$nextTick 是vue提供一个方法
       this.$nextTick(()=>{
            this.perviewImage()
       })
       //循环img列表给img注册点击事件
       //在事件处理函数中调用ImagePreview
     },
     perviewImage(){
       //1、获取文章内容DOM容器
       const articleContent=this.$refs['article-content']
       //2、得到所有的img标签
       const imgs=articleContent.querySelectorAll('img')
        //3、循环img列表给img注册点击事件
        //收集所有的图片的图片路径
        const imgPath=[]
        imgs.forEach((img,index)=>{
          imgPath.push(img.src)
           img.onclick=function(){
            //4、在事件处理函数中调用ImagePreview预览
             ImagePreview({
               images:imgPath,
               startPosition: index,
             })
           }
        })
     },
     //关注按钮
    async onFollow(){
       this.isFollowLoading=true
       if(this.article.is_followed){
         //已关注，取消关注
        const {data} = await delFollow(this.article.aut_id)
        console.log(data)
       }else{
         //没有关注，添加关注
         const {data} = await addFollow(this.article.aut_id)
          console.log(data)
       }
       //更新视图
       this.article.is_followed=!this.article.is_followed
       this.isFollowLoading=false
     },
     //收藏按钮
     async onCollected(){
       this.$toast.loading({
         message:'操作中...',
         forbidClick:true
       })
       if(this.article.is_collected){
         //已收藏，取消收藏
         await delCollected(this.articleId)

       }else{
         //没有收藏，添加收藏
         await addCollected(this.articleId)
       }
       //更新视图
       this.article.is_collected=!this.article.is_collected
       this.$toast.success(`${this.article.is_collected? '收藏成功':'取消收藏'}`)
     },
     //点赞按钮
    async onLike(){
         this.$toast.loading({
            message:'操作中...',
            forbidClick:true
          })
          if(this.article.attitude===1){
            //已点赞，取消点赞
            await delLike(this.articleId)
            this.article.attitude =-1
          }else{
            //没有点赞，添加点赞
            await addLike(this.articleId)
            this.article.attitude=1
          }
          //更新视图
          this.$toast.success(`${this.article.attitude===1? '点赞成功':'取消点赞'}`)
     },
     popShow(){
       this.isShow=true
     },
     onPostSuccess(comment){
       //把发布成功的评论数据对象放到评论列表顶部
       this.commtentList.unshift(comment)
       //更新评论总数量
       this.totalCommentCount++
       this.isShow=false

     },
     //回复评论
     onReply(comment){
       this.isReplyShow=true;
       //console.log(comment)
       this.replyComment=comment
     }
  },
};
</script>
<style lang="less" scoped>
.title{
  font-size: 20px;
  color: #3a3a3a;
  margin:0;
  padding:14px;
  line-height:24px;
  background: #ffffff;
}
.cell-desc{
   .user-name{
     font-size: 12px;
     line-height: 12px;
     color: #333;
   }
   .pubdata{
     font-size: 12px;
     line-height: 12px;
     color: #b4b4b4;
   }
   .avatar{
     width: 35px;
     height: 35px;
     margin-right: 8px;
   }
   .follow-btn{
     width: 85px;
     height: 29px;

   }
}
ul{
  list-style: unset;
}
.markdown-body{
  padding:14px;
  background: #fff;
}
.article-bottom{
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    height: 45px;
    display: flex;
    box-sizing: border-box;
    justify-content: space-around;
    align-items: center;
    background-color: #fff;
    border-top: 1px solid #d8d8d8;
    .comment-btn{
      width: 160px;
    }
    .van-icon {
      font-size: 28px;
    }
  }
  .article-wrap{
     position: fixed;
     left:0;
     right:0;
     top:46px;
     bottom:44px;
     overflow-y: auto;

  }
</style>
